package com.loong.rpc.protocol;

import com.loong.rpc.common.Invocation;
import com.loong.rpc.register.LocalRegister;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class HttpServletHandler {

    public void handler(HttpServletRequest req, HttpServletResponse resp) {
        try {
            Invocation invocation = (Invocation) new ObjectInputStream(req.getInputStream()).readObject();

            String interfaceName = invocation.getInterfaceName();
            Class<?> implClazz = LocalRegister.get(interfaceName);

            Method method = implClazz.getMethod(invocation.getMethodName(), invocation.getParameterTypes());

            String result = (String)method.invoke(implClazz.newInstance(), invocation.getParameters());

            IOUtils.write(result, resp.getOutputStream());

        } catch (IOException | ClassNotFoundException | NoSuchMethodException | IllegalAccessException |
                 InvocationTargetException | InstantiationException e) {
            throw new RuntimeException(e);
        }
    }

}
